/*
 *   Copyright 2006 Wei Lian <lianwei3@gmail.com>
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public License
 *   as published by the Free Software Foundation; either version 2
 *   of the License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include "header.h"

int
socket_send (int sock, char *buffer, int size)
{
  int ret, sent = 0;

  while (size)
    {
      ret = send (sock, buffer + sent, size, 0);
      if (ret == -1)
	{
	  printf ("SEND failed\n");
	  return -1;
	}
      if (ret == 0)
	break;
      sent += ret;
      size -= ret;
    }
  return sent;
}


int
socket_connect (int portnum)
{
  int sock;
  struct sockaddr_in serv_addr;
  struct hostent *server;
  ////

  server = gethostbyname ("127.0.0.1");
  if (server == NULL)
    {
      perror ("ERROR, no such host");
      return -2;
    }
  memset ((char *) &serv_addr, 0, sizeof (serv_addr));
  serv_addr.sin_family = AF_INET;
  memcpy ((char *) &serv_addr.sin_addr.s_addr,
	  (char *) server->h_addr, server->h_length);

  sock = socket (AF_INET, SOCK_STREAM, 0);
  if (sock == -1)
    {
      perror ("ERROR opening socket");
      return -3;
    }

  serv_addr.sin_port = htons (portnum);

  if (connect (sock, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) ==
      -1)
    {
      close (sock);
      return -1;
    }
  return sock;
}
